package lab4;

import java.awt.TextArea;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ConnectedClient extends Thread {
	private Socket sock;
	private BufferedReader input;
	private PrintWriter output;
	private TextArea text;

	public ConnectedClient(Socket s, TextArea text) throws IOException {
		sock = s;
		this.text = text;
		this.text.append("Подсоединеен новый пользователь с IP "
				+ s.getInetAddress().toString() + "\n");
		input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
		output = new PrintWriter(sock.getOutputStream());

	}

	@Override
	public void run() {

		try {
			while (sock.isConnected() && (Server.end == 0)) {
				synchronized (Server.clients) {
					String[] readed = new String[2];
					readed[0] = input.readLine();
					readed[1] = input.readLine();
					if ((readed[0] == null) || (readed[1] == null)) {
						this.text.append("Отсоединен пользователь с IP "
								+ sock.getInetAddress().toString() + "\n");
						break;
					} else {
						for (ConnectedClient c : Server.clients) {
							if (c.isAlive()) {
								c.send(readed[0]);
								c.send(readed[1]);
							}
						}
					}
				}
			}

		} catch (IOException e) {
			System.out.println("can't readline");
		}
	}

	public void send(String readed){
		output.println(readed);
		output.flush();
	}
}